﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class WikiListPage : PhoneApplicationPage
    {
        private object data = null;
        private Category kategori;
        private Wiki wiki;
        private bool firstLoaded;

        public WikiListPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                firstLoaded = false;
            else
                firstLoaded = true;

            if (kategori != null)
                FindWiki(JsonConvert.SerializeObject(kategori));
        }

        #region Event Handlers
        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            data = DataContext;
            if (firstLoaded && data != null)
            {
                if (data is Category)
                {
                    kategori = (Category)data;
                    pivotOne.Header = kategori.Kategori;
                    FindWiki(JsonConvert.SerializeObject(kategori));
                }
            }
        }

        #endregion

        private void NavigateToDetail(object selectedWiki)
        {
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = selectedWiki;
            Utility.GotoPage(this, "/View/WikiDetailPage.xaml");
        }

        private void FindWiki(string json)
        {
            string url = Config.Instance.WIKI_SERVICE_URL() + Config.FIND_ACTION_KEY;
            
            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(findWiki_UploadStringCompleted);            
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void findWiki_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                WikiList list = JsonConvert.DeserializeObject<WikiList>(e.Result);
                if (list == null || list.Count <= 0)
                {
                    listWikiDetail.ItemsSource = null;
                    MessageBox.Show("No wiki found");
                }
                else
                {
                    listWikiDetail.ItemsSource = list;
                    pivotWiki.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void listWikiDetail_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                wiki = (Wiki)e.AddedItems[0];

                ((ListBox)sender).SelectedIndex = -1;
                NavigateToDetail(wiki);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            Wiki wiki = new Wiki();
            wiki.Judul = "";
            wiki.Isi = "";
            wiki.Kategori = kategori;

            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = wiki;
            Utility.GotoPage(this, "/View/WikiFormPage.xaml");
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            pivotWiki.SelectedIndex = 1;
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxKeyword.Text.Length < 1)
            {
                MessageBox.Show("Keyword is empty.");
                return;
            }

            Wiki find = new Wiki();
            find.Judul = textBoxKeyword.Text;
            find.Isi = textBoxKeyword.Text;
            find.Kategori = kategori;
            FindWiki(JsonConvert.SerializeObject(find));
        }
        
    }
}